// uni iap

const ProviderType = {
  IAP: 'iap'
}

const IapTransactionState = {
  purchasing: "0", // A transaction that is being processed by the App Store.
  purchased: "1", // A successfully processed transaction.
  failed: "2", // A failed transaction.
  restored: "3", // A transaction that restores content previously purchased by the user.
  deferred: "4" // A transaction that is in the queue, but its final status is pending external action such as Ask to Buy.
};

class Iap {
  _channel = null;
  _channelError = null;
  _productIds = [];

  _ready = false;

  constructor(appleiapChannel) {
    this._channel = appleiapChannel;
  }

  getProduct(productIds = []) {
    console.log('子channel========='+JSON.stringify(this._channel));
    return new Promise((resolve, reject) => {
      this._channel.requestProduct(productIds, (res) => {
        console.log('res=========' + JSON.stringify(res));
        resolve(res);
      }, (err) => {
        reject(err);
      })
    });
  }

  // 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
  restoreCompletedTransactions(username) {
    return new Promise((resolve, reject) => {
      this._channel.restoreCompletedTransactions({
        manualFinishTransaction: true,
        username
      }, (res) => {
        resolve(res);
      }, (err) => {
        reject(err);
      })
    });
  }

  finishTransaction(transaction) {
    return new Promise((resolve, reject) => {
      this._channel.finishTransaction(transaction, (res) => {
        resolve(res);
      }, (err) => {
        reject(err);
      });
    });
  }

  get channel() {
    return this._channel;
  }
}

export {
  Iap,
  IapTransactionState
}
